import React, { useState } from "react";
import { Todo, createTodo, getVisibleTodos, initialTodos } from "./todos";

const TodoList: React.FC = () => {
  const [todos, setTodos] = useState<Todo[]>(initialTodos);
  const [showActive, setShowActive] = useState(false);

  // const visibleTodos = useMemo(() => getVisibleTodos(todos, showActive), [todos, showActive]);
  const visibleTodos = getVisibleTodos(todos, showActive);

  return (
    <>
      <label>
        <input type="checkbox" checked={showActive} onChange={e => setShowActive(e.target.checked)} />
        只显示未完成的事项
      </label>
      <br />
      <NewTodo onAdd={todo => setTodos([...todos, todo])} />
      <ul>
        {visibleTodos.map(todo => (
          <li key={todo.id}>{todo.completed ? <del>{todo.text}</del> : todo.text}</li>
        ))}
      </ul>
    </>
  );
};

interface NewTodoProps {
  onAdd: (todos: Todo) => void;
}
function NewTodo({ onAdd }: NewTodoProps) {
  const [text, setText] = useState("");

  function handleAddClick() {
    setText("");
    onAdd(createTodo(text));
  }

  return (
    <>
      <input value={text} onChange={e => setText(e.target.value)} />
      <button onClick={handleAddClick}>添加</button>
    </>
  );
}

export default TodoList;
